/**
 * 
 */
package com.zito.manager;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.downlove.common.RequestContext;
import com.downlove.common.StorageService;
import com.downlove.common.Storage.ImageInfo;
import com.downlove.database.POJO;
import com.zito.ErrMsgException;
import com.zito.bean.Articlephotos;

/**
 * @author YunHai.Jiang
 * 
 */
public class ArticlephotosManager {
	Articlephotos photo = new Articlephotos();
	int imageSize = 3000 * 1024;

	public Map<String, Object> uploadImages() throws ErrMsgException,
			IOException {
		RequestContext rc = RequestContext.get();
		Enumeration<String> files = rc.getFileNames();
		ImageInfo info = null;
		long tmpFileid = -1L;
		while (files.hasMoreElements()) {
			String filename = files.nextElement();
			File imgFile = rc.image(filename);
			if (imgFile.length() > imageSize) {
				throw new ErrMsgException("您上传的- " + imgFile.getName()
						+ " -图片过大，系统仅允许上传：" + imageSize / 1024 + "K 大小的文件");
			}

			info = StorageService.IMAGES.saveImage(imgFile).Thumbnail().getImageInfo();
			tmpFileid = Articlephotos
					.fromFileinfo(info, rc.param("identifies"));
		}
		Map<String, Object> tmpMap = new HashMap<String, Object>();
		tmpMap.put("info", info);
		tmpMap.put("tmpFileid", tmpFileid);
		return tmpMap;
	}

	/**
	 * 删除文章中指定的一个图片
	 * 
	 * @return
	 * @throws ErrMsgException
	 * @throws IOException
	 */
	public boolean deleteOneArticlePhoto() throws ErrMsgException,
			IOException {
		RequestContext rc = RequestContext.get();
		photo = new Articlephotos();
		photo.setId(rc.param("id", -1L));
		if (photo.getId() == -1L)
			return false;
		Articlephotos temp = photo.Get(photo.getId());
		boolean flag = photo.Delete();
		if (flag) {
			StorageService.EMPTY.delete(temp.getFileserverpath());
		}
		return flag;
	}

	public List<? extends POJO> list(Integer articleid) {
		return photo.forArticleList(articleid.longValue());
	}

}
